package com.itheima.filter;

import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.utils.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Zheng
 * @date: 2022/8/25 22:31
 * @description:
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String uri = req.getRequestURI();

        if (uri.contains("login") || uri.endsWith(".js") || uri.endsWith(".css") || uri.contains("images")
                || uri.endsWith(".ico") || uri.contains("styles") || uri.contains("plugins") || uri.contains("user/sms")) {
            chain.doFilter(req, resp);
            return;
        }

        Employee employee = (Employee) req.getSession().getAttribute("employee");

        if (employee != null) {

            //在这里，把员工的id，保存到ThreadLocal里面去！...
            BaseContext.setCurrentId(employee.getId());


            //3.2 如果取出来的对象不是 null, 就表明已经登录了。那么直接放行！
            chain.doFilter(req, resp);
            return;
        }

        //补充前端的过滤操作

        User user = (User) req.getSession().getAttribute("user");

        if (user != null) {
            BaseContext.setCurrentId(user.getId());

            chain.doFilter(req, resp);
            return;
        }

        if (uri.contains("front")) {
            resp.sendRedirect("/front/page/login.html");
        } else {
            resp.sendRedirect("/backend/page/login/login.html");
        }
    }
}
